package cn.uncode.springcloud.starter.web.exception;

import com.alibaba.csp.sentinel.slots.block.BlockException;

import cn.uncode.springcloud.starter.web.result.Message;
import cn.uncode.springcloud.starter.web.result.ResultCode;

import org.springframework.cloud.alibaba.sentinel.rest.SentinelClientHttpResponse;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;

import lombok.extern.slf4j.Slf4j;

/**
 * 异常处理工具类
 *
 * @author Juny
 */
@Slf4j
public final class ExceptionUtils {
	
	private ExceptionUtils() {}
	

	/**
	 * 抛异常
	 * @param key 自定信息key
	 * @param params 字符串对应的填充参数
	 */
	public static void throwRCException(String key, Object... params) {
		throw new RCException(Message.getRCode(key, params));
	}

	/**
	 * 抛验证异常
	 * @param key 自定信息key
	 * @param params 字符串对应的填充参数
	 */
	public static void throwException(String key, Object... params) {
		throw new RCException(Message.getRCode(key, params));
	}

	/**
	 * 业务异常
	 */
	public static void throwException(String message) {
		ResultCode code = ResultCode.FAILURE;
		throwException(code, message);
	}

	/**
	 * 抛验证异常
	 */
	public static void throwException(ResultCode code) {
		throw new RCException(code);
	}

	/**
	 * 抛验证异常
	 */
	public static void throwException(ResultCode code, String message) {
		code.setMessage(message);
		throw new RCException(code);
	}

	/**
	 * 处理限流异常
	 * @param request
	 * @param body
	 * @param execution
	 * @param ex
	 * @return
	 */
	public static SentinelClientHttpResponse handleSentinelException(HttpRequest request,
			byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
		log.error("Oops: " + ex.getClass().getCanonicalName(), ex);
		return new SentinelClientHttpResponse("custom block info");
	}


	/**
	 * 抛验证异常
	 */
	public static void throwException(Exception e) {
		ResultCode code = ResultCode.PARAM_VALID_ERROR;
		throwException(code, e.getMessage());
	}

	/**
	 *  抛参数校验 异常 .
	 *  异常code -1 。
	 * @param message 异常 msg
	 */
	public static void throwValidationException(String message) {
		ResultCode code = ResultCode.PARAM_VALID_ERROR;
		throwException(code, message);
	}

}
